package cn.q3c.parse.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import cn.keyvalue.ccf.base.BaseDAO;
import cn.q3c.parse.dao.object.Page;

public class PageDAO extends BaseDAO{

	private static final Logger logger = Logger.getLogger(PageDAO.class);
	
	/**
	 * 写入
	 * @param page
	 * @throws SQLException
	 */
	public void addPage( Page page ) throws SQLException
	{
		Connection conn = null;
		
		try
		{
			String sql = "insert into t_pages(url,headtitle,headkeywords,headdescription,bodytitle,bodykeywords,bodycontent,bodyimages,backup1,backup2,backup3,backup4,project,cdate,pdate)"
					+ " values(?,?,?,?,?,?,?,?,?,?,?,?,?,now(),?)";

			Object[] objs = new Object[] {
					StringUtils.trimToEmpty(page.getUrl()),
					StringUtils.trimToEmpty(page.getHeadtitle()),
					StringUtils.trimToEmpty(page.getHeadkeywords()),
					StringUtils.trimToEmpty(page.getHeaddescription()),
					StringUtils.trimToEmpty(page.getBodytitle()),
					StringUtils.trimToEmpty(page.getBodykeywords()),
					StringUtils.trimToEmpty(page.getBodycontent()),
					StringUtils.trimToEmpty(page.getBodyimages()),
					page.getBackup1()==null?0:page.getBackup1(), 
					page.getBackup2()==null?0:page.getBackup2(),
					StringUtils.trimToEmpty(page.getBackup3()),
					StringUtils.trimToEmpty(page.getBackup4()),
					StringUtils.trimToEmpty(page.getProject()), page.getPdate()
			};
			
			conn = this.getDataSource().getConnection();
			this.update(conn, sql, objs);// 批量提交
		}
		catch( Exception e )
		{
			logger.error("写入page信息异常", e);
		}
		finally
		{
			DbUtils.close(conn);
		}
	}
	
	
	public List<Page> getPageList( int limit, String project ) throws SQLException
	{
		Connection conn = null;
		
		try
		{
			String sql = "select * from t_pages where project=? order by nid desc limit ?";
			Object[] params = new Object[]{project, limit};
			
			conn = this.getDataSource().getConnection();
			DbUtils.close(conn);
			return (List<Page>)this.query(conn, sql, new BeanListHandler<Page>(Page.class), params);
		}
		catch( Exception e )
		{
			logger.error("获取page信息异常", e);
		}
		finally
		{
			DbUtils.close(conn);
		}
		
		return null;
	}
}
